﻿using System.Web.Mvc;
using TSV.Models;
using TSV.Library.Common;
using TSV.Areas.Administration.Models;
using System.Drawing;
using System.Drawing.Text;
using System;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Configuration;
using TSV.Library.Utils;


namespace TSV.Controllers
{
    public class RegisterController : BaseViewController
    {
        private OwnerStudentCardDao ownerStudentDao = new OwnerStudentCardDao();
        private CollaboratorDao collaboratorDao = new CollaboratorDao();

        #region Captcha
        public void SetCaptcha()
        {

            //*** Editable Values
            int[] BackgroundColor = new int[] { 255, 255, 255 };// The 3 numbers represent in order RED, GREEN, BLUE for the captcha's background color
            bool RandomBackgroundNoiseColor = false;// True / False. If you choose True, BackgroundNoiseColor will not apply 
            bool RandomTextColor = true;// True / False. If you choose True, TextColor will not apply 
            int[] BackgroundNoiseColor = new int[] { 150, 150, 150 };// The 3 numbers represent in order RED, GREEN, BLUE
            int[] TextColor = new int[] { 100, 100, 100 };// The 3 numbers represent in order RED, GREEN, BLUE
            HatchStyle BackgroundNoiseTexture = HatchStyle.Divot;// replace ".Min" with any of the following: Horizontal, Vertical, ForwardDiagonal, BackwardDiagonal, Cross, DiagonalCross, Percent05, Percent10, Percent20, Percent25, Percent30, Percent40, Percent50, Percent60, Percent70, Percent75, Percent80, Percent90, LightDownwardDiagonal, LightUpwardDiagonal, DarkDownwardDiagonal, DarkUpwardDiagonal, WideDownwardDiagonal, WideUpwardDiagonal, LightVertical, LightHorizontal, NarrowVertical, NarrowHorizontal, DarkVertical, DarkHorizontal, DashedDownwardDiagonal, DashedUpwardDiagonal, DashedHorizontal, DashedVertical, SmallConfetti, LargeConfetti, ZigZag, Wave, DiagonalBrick, HorizontalBrick, Weave, Plaid, Divot, DottedGrid, DottedDiamond, Shingle, Trellis, Sphere, SmallGrid, SmallCheckerBoard, LargeCheckerBoard, OutlinedDiamond, SolidDiamond, LargeGrid, Min, Max
            int length = 6;// Number of characters to generate
            //*** END Editable Valuese

            int height = 60;
            int width = 300;
            width = width + ((length - 6) * 30);
            Random ranRotate = new Random();

            string strText = System.Guid.NewGuid().ToString();
            strText = strText.Replace("-", String.Empty);
            strText = strText.Substring(0, length);
            TempData["CaptchaValue"] = strText;

            Bitmap bmpCanvas = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            Graphics graCanvas = Graphics.FromImage(bmpCanvas);
            RectangleF recF = new RectangleF(0, 0, width, height);
            Brush bruBackground = default(Brush);
            SolidBrush letterBrush = default(SolidBrush);

            if (RandomBackgroundNoiseColor == true)
            {
                bruBackground = new HatchBrush(BackgroundNoiseTexture, Color.FromArgb((ranRotate.Next(0, 255)), (ranRotate.Next(0, 255)), (ranRotate.Next(0, 255))), Color.FromArgb(BackgroundColor[0], BackgroundColor[1], BackgroundColor[2]));
            }
            else
            {
                bruBackground = new HatchBrush(BackgroundNoiseTexture, Color.FromArgb(238, 221, 130), Color.FromArgb(238, 222, 170));
            }

            graCanvas.FillRectangle(bruBackground, recF);

            if (RandomTextColor == true)
            {
                letterBrush = new SolidBrush(Color.FromArgb((ranRotate.Next(0, 255)), (ranRotate.Next(0, 255)), (ranRotate.Next(0, 255))));
            }
            else
            {
                letterBrush = new SolidBrush(Color.FromArgb(139, 69, 19));
            }

            System.Drawing.Drawing2D.Matrix matRotate = new System.Drawing.Drawing2D.Matrix();
            int i = 0;
            for (i = 0; i <= strText.Length - 1; i++)
            {
                matRotate.Reset();
                int intChars = strText.Length;
                int x = width / (intChars + 1) * i;
                int y = height / 2;
                //matRotate.RotateAt(ranRotate.Next(-30, 30), new PointF(width / (intChars + 1) * i, height * 0.5) );
               // matRotate.RotateAt(ranRotate.Next(-30, 30), new PointF(x, y));
                graCanvas.Transform = matRotate;
                if (i == 0)
                {
                    //draw ‘the text on our image
                    //graCanvas.DrawString(strText.Chars(i), new Font("Comic Sans MS", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, height * 0.4);
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Times New Roman", 30, FontStyle.Bold), letterBrush, 20, 10);
                }
                else if (i == 1)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Arial", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else if (i == 2)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Times New Roman", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else if (i == 3)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Georgia", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else if (i == 4)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Verdana", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else if (i == 5)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Geneva", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Verdana", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
                }
                graCanvas.ResetTransform();
            }
            //Response.ContentType = "image/GIF";
            bmpCanvas.Save(Response.OutputStream, ImageFormat.Gif);
            graCanvas.Dispose();
            bmpCanvas.Dispose();
        }
        #endregion
        public ActionResult RegisterSuccess()
        {
            return View();
        }

        #region Collaborator
        public ActionResult Collaborator()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Collaborator(Collaborator collaborator, FormCollection collection)
        {
            try
            {

                string gender = collection.GetValues("Gender")[0];
                if (gender.Equals("Nam"))
                {
                    collaborator.Gender = true;
                }
                else
                {
                    collaborator.Gender = false;
                }
                if (collection["txtCapcha"] == (string)TempData["CaptchaValue"])
                {
                    // TODO: Add insert logic here
                    Message msg = collaboratorDao.Insert(collaborator);
                    try
                    {
                        string from_email = ConfigurationManager.AppSettings["from_email"];
                        string host = ConfigurationManager.AppSettings["mailserver_host"];
                        string port = ConfigurationManager.AppSettings["mailserver_port"];
                        string poster = "Thẻ Giải Trí";
                        string subject = "Thông tin từ thegiaitri.com";
                        string body = "Chào bạn <b>" + collaborator.FullName + "</b>,<br/>";
                        body += "Bạn đã đăng ký làm cộng tác viên thành công trên website thegiaitri.com.<br/>";
                        body += "Chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất.<br/>";
                        body += "Cảm ơn bạn đã quan tâm tới dịch vụ của chúng tôi";
                        WebUtils.SendMail(host, port, from_email, poster, collaborator.Email,"", subject, body);
                    }catch
                    { }
                    TempData["MessageSuccess"] = "Bạn đã đăng ký làm cộng tác viên của Thẻ Giải Trí thành công !";
                    return Redirect("/thong-bao.html");
                }
                else
                {
                    Message msg = new Message(MessageConstants.E0042, MessageType.Error);
                    ShowAlertMessage(msg);
                    return View();
                }
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region Owner Student Card
        public ActionResult Card()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Card(OwnerStudentCard OSC, FormCollection collection)
        {
            Message msg = null;
            //Check capcha here
            if (collection["txtCapcha"] != (string)TempData["CaptchaValue"])
            {
                msg = new Message(MessageConstants.E0042, MessageType.Error);
                ShowAlertMessage(msg);
                return View();

            }
            try
            {
                string gender = collection.GetValues("Gender")[0];
                //string isCheckReceive = collection.Get("chkReceive");
                if (gender.Equals("Nam"))
                {
                    OSC.Gender = true;
                }
                else
                {
                    OSC.Gender = false;
                }

                // TODO: Add insert logic here
                msg = ownerStudentDao.Insert(OSC);

                if (msg.MsgType != MessageType.Error)
                {
                    //==>Temp for send mail to client

                    string from_email = ConfigurationManager.AppSettings["from_email"];
                    string host = ConfigurationManager.AppSettings["mailserver_host"];
                    string port = ConfigurationManager.AppSettings["mailserver_port"];
                    string poster = "Thẻ Giải Trí";
                    string subject = "Thông tin từ thegiaitri.com";
                    string body = "Chào bạn <b>" + OSC.FullName + "</b>,<br/>";
                    body += "Bạn đã đăng ký sở hửu thẻ sinh viên thành công trên website thegiaitri.com.<br/>";
                    body += "Chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất.<br/>";
                    body += "Cảm ơn bạn đã quan tâm tới dịch vụ của chúng tôi";
                    WebUtils.SendMail(host, port, from_email, poster, OSC.Email, "", subject, body);

                    //<==
                    TempData["MessageSuccess"] = "Bạn đã đăng ký sở hữu Thẻ Giải Trí thành công !";
                    return Redirect("/thong-bao.html");
                }
                return RedirectToAction("Index");

            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region Member
        public ActionResult Member()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Member(BusinessRegister BR, FormCollection collection)
        {
            string thu = (string)TempData["thu"];
            BusinessRegisterDao dao = new BusinessRegisterDao();
            Message msg = null;
            //Check capcha here
            if (collection["txtCapcha"] != (string)TempData["CaptchaValue"])
            {
                msg = new Message(MessageConstants.E0042, MessageType.Error);
                ShowAlertMessage(msg);
                return View();

            }
            else
            {
                try
                {

                    // TODO: Add insert logic here
                    msg = dao.Insert(BR);

                    if (msg.MsgType != MessageType.Error)
                    {
                        //==>Temp for send mail to client

                        string from_email = ConfigurationManager.AppSettings["from_email"];
                        string host = ConfigurationManager.AppSettings["mailserver_host"];
                        string port = ConfigurationManager.AppSettings["mailserver_port"];
                        string poster = "Thẻ giải trí";
                        string subject = "Thông tin từ thegiaitri.com";
                        string body = "Kính chào doanh nghiệp <b>" + BR.BusinessName + "</b>,<br/>";
                        body += "Doanh nghiệp bạn đã đăng ký làm thành viên của thegiaitri.com.<br/>";
                        body += "Chúng tôi sẽ liên hệ với quý doanh nghiệp trong thời gian sớm nhất.<br/>";
                        body += "Cảm ơn bạn đã quan tâm tới dịch vụ của chúng tôi";

                        WebUtils.SendMail(host, port, from_email, poster, BR.Email, "", subject, body);

                        //<==
                        TempData["MessageSuccess"] = "Bạn đã đăng ký làm thành viên của Thẻ Giải Trí thành công !";
                        return Redirect("/thong-bao.html");
                    }
                    else
                    {

                        ShowAlertPopup(msg);
                    }


                }
                catch
                {
                    return View();
                }
            }
            return View();
        }
        #endregion
    }
}
